package face.pay.sharing.biz;

import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class OrderEndSharingBiz {

    private final static   String domain    = "api.mch.weixin.qq.com";

    private final static   String urlSuffix = "/secapi/pay/profitsharingfinish";

    public Boolean sharingEnd(WxApiConfig wxApiConfig, OrderInfo orderInfo, EnterpriseInfo enterpriseInfo){
        try{
                log.info("结束分账");
                Long orderId = orderInfo.getId();

                String appId = wxApiConfig.getAppID();
                String apiKey = wxApiConfig.getKey();
                String mchId = wxApiConfig.getMchID();

                String tradeNo = orderInfo.getTradeNo();

                String subMchId = enterpriseInfo.getWxSubMchId();

                WXPayRequest wxPayRequest = new WXPayRequest(wxApiConfig);

                String nonce_str = WXPayUtil.generateNonceStr();

                Map<String, String> map = new HashMap<>();
                map.put("mch_id", mchId);
                map.put("nonce_str", nonce_str);
                map.put("sub_mch_id", subMchId);
                map.put("appid", appId);
                map.put("transaction_id", tradeNo);
                map.put("out_order_no", UUID.randomUUID().toString());
                map.put("description", "分账已经完结");

                String xml = WXPayUtil.generateSignedXml(map, apiKey, WXPayConstants.SignType.HMACSHA256);

                String result = wxPayRequest.requestOnce(domain, urlSuffix, xml, true);
                log.info("返回结果 " + result);
                Map<String, String> resultMap = WXPayUtil.xmlToMap(result);

                Boolean isSuccess = WXPayUtil.isSuccess(resultMap);
                if(isSuccess){
                    return  true;
                }else {
                    /**
                     * 结束订单失败
                     */
                    orderInfo.setSharing(-2);
                }

        }catch (Exception e){
            orderInfo.setSharing(-2);
            log.error("分账异常");
        }
        return  false;
    }

}
